package net.xdclass.interceptor;

import groovyjarjarantlr4.v4.runtime.misc.Nullable;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.common.LoginUser;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.utils.CommonUtil;
import net.xdclass.utils.JWTUtil;
import net.xdclass.utils.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;


@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    public static final ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //遇到options请求直接放行
        if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())){
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }
        String accessToken = request.getHeader("token");
        if (StringUtils.isBlank(accessToken)) {
            request.getParameter("accessToken");
        }
        if (StringUtils.isNotBlank(accessToken)){
            //解密
            Claims claims = JWTUtil.checkJWT(accessToken);
            if (claims == null) {
                //未登录
                CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
                return false;
            }
            Long accountNo = Long.parseLong(claims.get("account_no").toString());
            String headImg = (String)(claims.get("head_img").toString());
            String userName = (String)(claims.get("username").toString());
            String  phone  = (String)(claims.get("phone").toString());
            String  mail = (String) (claims.get("mail").toString());
            String  auth = (String) (claims.get("auth").toString());
            LoginUser loginUser = LoginUser.builder()
                    .accountNo(accountNo)
                    .headImg(headImg)
                    .username(userName)
                    .phone(phone)
                    .mail(mail)
                    .auth(auth)
                    .build();
           //方式一 request.setAttribute("login_user",loginUser);
            //使用ThreadLocal
            threadLocal.set(loginUser);
            return true;
        }
        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

        threadLocal.remove();
    }
}
